package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.kh.KHDBConfig;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.elite.Util;
import net.sf.json.JSONObject;
import cn.com.kh.KHUtil;

/**
 *
 * @author xrm
 * @use 更新合同状态--智能工单回写
 *
 */
public class GetupdateStorecontract implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(GetupdateStorecontract.class);
    private String charset = "utf-8"; //设置字符集
    private int timeout = 100000; //设置请求超时时间
    private int enableSSLflag = 1;

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        JSONObject result = new JSONObject();
        def smap, oJson, SaveResult;
        try {
            //获取客户端传参
            def r_sfStorecontractoid = Util.filterForObject(request.getParameter("sfStorecontractoid")); //获取json字符串
            def r_state = Util.filterForObject(request.getParameter("state")); //获取json字符串
            log.debug("NGS传参 Storecontractoid:" + r_sfStorecontractoid + " state:" + r_state);

            // 退租档位ID
            if (KHUtil.isNull(r_sfStorecontractoid)) {
                result.put("code", "0");
                result.put("msg", "调用一体化信息异常(更新档位ID),请确认当前工单是否有档位信息,如果存在档位信息请检查一体化合同状态");
                return result
            }

            // 退租时间
            if (KHUtil.isNull(r_state)) {
                result.put("code", "0");
                result.put("msg", "调用一体化信息异常(更新状态),请确认当前工单是否有档位信息,如果存在档位信息请检查一体化合同状态");
                return result
            }

            Map<String, String> map = new HashMap<String, String>();
            map.put("sfStorecontractoid", r_sfStorecontractoid);
            map.put("state", r_state);
            map.put("key", "ca3c64a49d1f11ecbed6d703198897725e7aba55");
            def ASCIIMD5 = KHUtil.ASCIIORDER(map);
            log.debug("接口返回:" + ASCIIMD5);
            oJson = CustHttpPort(eliteBean, ASCIIMD5); //调用接口方法
            log.debug("接口返回:" + oJson);
            return oJson;

        } catch (Exception e) {
            log.error("errormsg:", e)
            result.put("code", "-1");
            result.put("msg", "调用失败！");
            return result;
        }
    }

    /**
     *
     * @use 更新合同状态--智能工单回写
     * @param eliteBean
     * @param
     * @return
     */
    private String CustHttpPort(EliteBean eliteBean, ASCIIMD5) {
        JSONObject result = new JSONObject();
        String url = "";
        try {
            //获取接口地址
            url = KHDBConfig.getAPIURL(eliteBean, "updateStorecontract");
            log.debug("获取接口地址:" + url);

            def postmap = Util.doHttpPost(url, ASCIIMD5.toString(), charset, timeout, enableSSLflag);
            log.debug("一体化系统’updateStorecontract‘接口返回:" + postmap);
            JSONObject obj = JSONObject.fromObject(postmap);
            if (obj.getInt("status") != 200) {
                result.put("code", "-1");
                result.put("msg", obj.getString("message"));
                return result;
            } else {
                return obj;
            }

        } catch (Exception e) {
            log.error("errormsg:", e)
            result.put("code", "-1");
            result.put("msg", "更新合同状态 调用一体化接口错误");
            return result;
        }
    }

    public static String ASCIIORDER(Map<String, String> map) {
        JSONObject result = new JSONObject();
        // 对所有传入参数按照字段名的 ASCII 码从小到大排序
        List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(map.entrySet());
        Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {
            public int compare(Map.Entry<String, String> A, Map.Entry<String, String> B) {
                return (A.getKey()).toString().compareTo(B.getKey());
            }
        })

        // 构造签名键值的格式
        StringBuilder stringsign = new StringBuilder();
        StringBuilder sign = new StringBuilder();
        for (Map.Entry<String, String> item : infoIds) {
            if (item.getKey() != null || item.getKey() != "") {
                String key = item.getKey();
                String val = item.getValue();
                if (!(val == "" || val == null)) {
                    sign.append(key + "=" + URLEncoder.encode(val, "UTF-8") + "&");
                }
                if (!(val == "" || val == null) && !(key == "key")) {
                    stringsign.append(key + "=" + val + "&");
                }
            }
        }
        String md5sign = Util.getMD5Str(sign.substring(0, sign.length() - 1));
        return stringsign.append("sign=" + md5sign);
    }
}